package com.ruoyi.xuexiao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.constant.DataConstant;
import com.ruoyi.constant.v3.RwZtV3Enum;
import com.ruoyi.xuexiao.domain.entity.BasicRegion;
import com.ruoyi.xuexiao.domain.entity.RwTzV3;
import com.ruoyi.xuexiao.domain.param.RwTzV3VParam;
import com.ruoyi.xuexiao.domain.param.SuperviseParam;
import com.ruoyi.xuexiao.mapper.BasicRegionMapper;
import com.ruoyi.xuexiao.mapper.RwTzV3Mapper;
import com.ruoyi.xuexiao.service.RwTzV3Service;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 填报统计
 * @author 田江余
 */
@Service
@AllArgsConstructor
public class RwTzV3ServiceImpl extends ServiceImpl<RwTzV3Mapper, RwTzV3> implements RwTzV3Service {

    private RwTzV3Mapper rwTzV3Mapper;

    private BasicRegionMapper basicRegionMapper;

    /**
     * 上下半年统计
     *
     * @param
     * @return
     * @author 田江余
     */
    @Override
    public Map<String, Object> selectRwTzV3Year(RwTzV3VParam rwTzV3DTO) {
        Map<String, Object> map = new HashMap<>();
        //上半年
        List<RwTzV3VParam> selectRwTzV3 = rwTzV3Mapper.selectRwTzV3Year(rwTzV3DTO);
        //下半年
        List<RwTzV3VParam> selectRwTzV3Year = rwTzV3Mapper.selectRwTzV3(rwTzV3DTO);
        map.put("selectRwTzV3", selectRwTzV3);
        map.put("selectRwTzV3Year", selectRwTzV3Year);

        return map;
    }

    /**
     * 上下半年省级核查任务进度
     *
     * @param rwTzV3DTO
     * @return
     * @author 田江余
     */
    @Override
    public List<RwTzV3VParam> InTheFirstHalfOfTheYear(RwTzV3VParam rwTzV3DTO) {
        ArrayList<RwTzV3VParam> rwTzV3DTOS = new ArrayList<>();

        LambdaQueryWrapper<RwTzV3> rwTzV3LambdaQueryWrapper = getRwTzV3LambdaQueryWrapper(1, 1);
        Long sl = rwTzV3Mapper.selectCount(rwTzV3LambdaQueryWrapper);
        extracted(sl, rwTzV3DTOS);

        LambdaQueryWrapper<RwTzV3> tzV3LambdaQueryWrapper = getRwTzV3LambdaQueryWrapper(1, 2);
        Long xl = rwTzV3Mapper.selectCount(tzV3LambdaQueryWrapper);
        extracted(xl, rwTzV3DTOS);

        return rwTzV3DTOS;
    }

    /**
     * 查询条件
     *
     * @author 田江余
     */
    private static LambdaQueryWrapper<RwTzV3> getRwTzV3LambdaQueryWrapper(Integer rwjb, Integer sxbn) {
        LambdaQueryWrapper<RwTzV3> rwTzV3LambdaQueryWrapper = new LambdaQueryWrapper<>();
        //任务数量
        rwTzV3LambdaQueryWrapper.eq(RwTzV3::getRwjb, rwjb);
        //上半年
        rwTzV3LambdaQueryWrapper.eq(RwTzV3::getSxbn, sxbn);
        //已填报
        rwTzV3LambdaQueryWrapper.in(RwTzV3::getRwzt, RwZtV3Enum.getCodes());
        return rwTzV3LambdaQueryWrapper;
    }

    /**
     * 计算封装数据
     *
     * @author 田江余
     */
    private void extracted(Long sum, ArrayList<RwTzV3VParam> rwTzV3DTOS) {
        RwTzV3VParam rwTzV3DTO = new RwTzV3VParam();
        //填报百分比
        double reportPercentage = (double) rwTzV3DTOS.size() / sum * 100;
        rwTzV3DTO.setTotalRwsl(sum);//任务数量
        rwTzV3DTO.setYtb(rwTzV3DTOS.size());//已填报
        rwTzV3DTO.setBfb(Math.round(reportPercentage));//填报百分比，取整，不要小数点
        rwTzV3DTOS.add(rwTzV3DTO);
    }

    /**
     * 上半年市级核查任务进度
     *
     * @author 田江余
     */
    @Override
    public List<RwTzV3VParam> inTheSecondHalfOfTheYear(ArrayList<RwTzV3VParam> rwTzV3DTOS, SuperviseParam supervise) {
        // 任务数量
        LambdaQueryWrapper<RwTzV3> lambdaQueryWrapper = new LambdaQueryWrapper<>();


        //上下半年，1,2
        lambdaQueryWrapper.eq(RwTzV3::getSxbn, supervise.getYear());

        lambdaQueryWrapper.eq(RwTzV3::getRwjb, 2);
        Long sl = rwTzV3Mapper.selectCount(lambdaQueryWrapper);


        // 已填报
        LambdaQueryWrapper<RwTzV3> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(RwTzV3::getRwzt, RwZtV3Enum.getCodes());
        // 查询已填报的任务列表
        List<RwTzV3> rwTzV3s = rwTzV3Mapper.selectList(wrapper);
        // 创建一个新的列表来存储查询结果
        List<RwTzV3VParam> resultDTOs = new ArrayList<>();
        // 用于存储每个市的任务数量和填报数量
        Map<String, RwTzV3VParam> cityTaskAndSubmissionCountMap = new HashMap<>();
        for (RwTzV3 rwTzV3 : rwTzV3s) {
            // 市名称
            String sjcs = basicRegionMapper.selectOne(
                    new LambdaQueryWrapper<BasicRegion>()
                            .eq(BasicRegion::getAdcd, rwTzV3.getSxzqdm())
            ).getAdnm();
            // 检查市名称是否已经存在于结果列表中
            if (!cityTaskAndSubmissionCountMap.containsKey(sjcs)) {
                // 创建一个新的RwTzV3DTO对象来存储当前市的信息
                RwTzV3VParam rwTzV3DTO = new RwTzV3VParam();
                // 填报数量
                rwTzV3DTO.setYtb(rwTzV3DTOS.size());
                // 任务数量
                rwTzV3DTO.setTotalRwsl(sl);
                // 市名称
                rwTzV3DTO.setSjcs(sjcs);
                // 将当前市的信息添加到结果列表中
                resultDTOs.add(rwTzV3DTO);
                // 将市名称添加到map中
                cityTaskAndSubmissionCountMap.put(sjcs, rwTzV3DTO);
            }
            // 增加任务数量和填报数量
            RwTzV3VParam cityInfo = cityTaskAndSubmissionCountMap.get(sjcs);
            cityInfo.setTotalRwsl(cityInfo.getTotalRwsl() + 1);
            cityInfo.setYtb(cityInfo.getYtb() + 1);

            double percent = cityInfo.getYtb() / (double)cityInfo.getTotalRwsl() * 100;
            // 向下取整
            int wholeNumberBfb = (int) Math.floor(percent);
            // 现在bfb字段只有整数部分，没有小数点
            cityInfo.setBfb(wholeNumberBfb);
        }
        // 返回查询结果列表
        return resultDTOs;
    }

    /**
     * 上/下半年县级核查任务进度
     *
     * @return
     * @author 田江余
     */


    @Override
    public List<BasicRegion> inTheSecondHalfOf(SuperviseParam supervise) {

        // 查询所有数据
        List<BasicRegion> basicRegionse = basicRegionMapper.selectList(null);
        // 过滤出所有市级行政区
        List<BasicRegion> cityRegions = basicRegionse.stream()
                .filter(r -> r.getLevel() == DataConstant.REGION_LEVEL_OF_CITY)
                .collect(Collectors.toList());
        // 合并数据库查询
        Map<String, BasicRegion> cityRegionMap = cityRegions.stream()
                .collect(Collectors.toMap(BasicRegion::getAdcd, Function.identity()));

        // 为每个市级行政区设置其下一级的县级行政区列表
        List<BasicRegion> cityAndCountyRegions = cityRegions.stream()
                .map(city -> {
                    city.setChild(basicRegionse.stream()
                            .filter(r -> {
                                int i = r.getAdcd().length() - 2;
                                boolean f = (r.getAdcd().substring(0, i) + "00").equals(city.getAdcd());
                                return r.getLevel() == DataConstant.REGION_LEVEL_OF_COUNTY && f;
                            })
                            .collect(Collectors.toList()));
                    return city;
                })
                .collect(Collectors.toList());
        // 查询所有县级行政区
        List<BasicRegion> countyRegions = basicRegionMapper.selectList(new LambdaQueryWrapper<BasicRegion>()
                .eq(BasicRegion::getLevel, DataConstant.REGION_LEVEL_OF_COUNTY));

        // 获取所有县级行政区的代码
        List<String> countyCodes = countyRegions.stream()
                .map(BasicRegion::getAdcd)
                .collect(Collectors.toList());

        // 批量查询县级行政区数量和特定状态的县级行政区数量
        List<RwTzV3> rwTzV3List = rwTzV3Mapper.selectList(new LambdaQueryWrapper<RwTzV3>()
                .in(RwTzV3::getSxbn, supervise.getYear())
                .in(RwTzV3::getXxzqdm, countyCodes)
                .in(RwTzV3::getRwzt, RwZtV3Enum.getCodes()));

        // 统计数量
        Map<String, Long> rwTzV3CountListMap = rwTzV3List.stream()
                .collect(Collectors.groupingBy(RwTzV3::getXxzqdm, Collectors.counting()));
        // 更新BasicRegions对象
        cityRegionMap.values().forEach(cityRegion -> {
            for (BasicRegion basicRegion : cityRegion.getChild()) {
                basicRegion.setTotalRwsl(rwTzV3CountListMap.getOrDefault(basicRegion.getAdcd(), 0L));
                basicRegion.setYtb(rwTzV3CountListMap.getOrDefault(basicRegion.getAdcd(), 0L));
                if (basicRegion.getTotalRwsl() > 0) { // 确保totalRwsl不为0，避免除以0的错误
                    basicRegion.setBfb((basicRegion.getYtb().doubleValue() / basicRegion.getTotalRwsl()) * 100);
                } else {
                    basicRegion.setBfb(0.0); // 如果totalRwsl为0，则bfb为0
                }
            }
            //过滤为0的数据
            List<BasicRegion> basicRegions = cityRegion.getChild().stream().filter(e -> e.getTotalRwsl() != 0).collect(Collectors.toList());
            cityRegion.setChild(basicRegions);
            //计算市相加数量
            cityRegion.setTotalRwsl(basicRegions.stream().mapToLong(BasicRegion::getTotalRwsl).sum());
            cityRegion.setYtb(basicRegions.stream().mapToLong(BasicRegion::getYtb).sum());
            if (cityRegion.getTotalRwsl() > 0) { // 确保totalRwsl不为0，避免除以0的错误
                cityRegion.setBfb((cityRegion.getYtb().doubleValue() / cityRegion.getTotalRwsl()) * 100);
            } else {
                cityRegion.setBfb(0.0); // 如果totalRwsl为0，则bfb为0
            }
        });
        return cityAndCountyRegions;
    }

    /**
     * 上下半年常规任务每月填报情况
     */
    @Override
    public List<RwTzV3VParam> selectMyY(SuperviseParam supervise) {
        ArrayList<RwTzV3VParam> tzV3Vos = new ArrayList<>();
        // 根据年份选择不同的统计方法
        if (supervise.getYear() == 1) {
            if (supervise.getCityName() != null){
                List<RwTzV3VParam> rwTzV3Vos = rwTzV3Mapper.selectY(supervise.getCityName());
                getMonth(rwTzV3Vos, tzV3Vos,supervise.getCityName());
            }else {
                List<RwTzV3VParam> rwTzV3Vos = rwTzV3Mapper.selectBKY();
                getMonth(rwTzV3Vos, tzV3Vos,supervise.getCityName());
            }
            return tzV3Vos;
        } else {
            if (supervise.getCityName() != null){
                List<RwTzV3VParam> rwTzV3Vos = rwTzV3Mapper.selectXy(supervise.getCityName());
                getMonth(rwTzV3Vos, tzV3Vos,supervise.getCityName());
            }else {
                List<RwTzV3VParam> rwTzV3Vos = rwTzV3Mapper.selectKy();
                getMonth(rwTzV3Vos, tzV3Vos,supervise.getCityName());
            }
            return tzV3Vos;
        }
    }


    /**
     * 上/下半年常规任务每月审核
     *
     * @return
     */
    @Override
    public List<RwTzV3VParam> selectSh(SuperviseParam supervise) {
        ArrayList<RwTzV3VParam> tzV3Vos = new ArrayList<>();
        // 根据年份选择不同的统计方法
        if (supervise.getYear() == 1) {
            if (supervise.getCityName() != null){
                List<RwTzV3VParam> rwTzV3Vos = rwTzV3Mapper.selectSh(supervise.getCityName());
                getMonth(rwTzV3Vos, tzV3Vos,supervise.getCityName());
            }else {
                List<RwTzV3VParam> rwTzV3Vos = rwTzV3Mapper.selectKh();
                getMonth(rwTzV3Vos, tzV3Vos,supervise.getCityName());
            }
            return tzV3Vos;
        } else {
            if (supervise.getCityName() != null){
                List<RwTzV3VParam> rwTzV3Vos = rwTzV3Mapper.selectXSh(supervise.getCityName());
                getMonth(rwTzV3Vos, tzV3Vos,supervise.getCityName());
            }else {
                List<RwTzV3VParam> rwTzV3Vos = rwTzV3Mapper.selectKSh();
                getMonth(rwTzV3Vos, tzV3Vos,supervise.getCityName());
            }
            // 下半年每月填报统计
            return tzV3Vos;
        }
    }


    /**
     * 获取对应月份的数据
     *
     * @param rwTzV3Vos
     * @param tzV3Vos
     */
    private void getMonth(List<RwTzV3VParam> rwTzV3Vos, ArrayList<RwTzV3VParam> tzV3Vos, String cityName) {
        Map<Long, List<RwTzV3VParam>> monthMap = rwTzV3Vos.stream().collect(Collectors.groupingBy(RwTzV3VParam::getMonth));
        for (long i = 1L; i <= 12L; i++) {
            RwTzV3VParam rwTzV3Vo = new RwTzV3VParam();
            List<RwTzV3VParam> rwTzV3VoList = monthMap.get(i);
            if (rwTzV3VoList != null && !rwTzV3VoList.isEmpty()) {
                rwTzV3Vo.setMonth(i);
                rwTzV3Vo.setYtb(rwTzV3VoList.stream().mapToInt(RwTzV3VParam::getYtb).sum());

            } else {
                //默认值
                rwTzV3Vo.setMonth(i);
                rwTzV3Vo.setYtb(0);
            }
            LambdaQueryWrapper<BasicRegion> wrapper = new LambdaQueryWrapper<>();
            LambdaQueryWrapper<BasicRegion> eq = wrapper.eq(BasicRegion::getAdcd, cityName);
            List<BasicRegion> basicRegions = basicRegionMapper.selectList(eq);
            for (BasicRegion basicRegion : basicRegions) {
                if (basicRegion!=null){
                    rwTzV3Vo.setAdnm(basicRegion.getAdnm());
                }
            }
            tzV3Vos.add(rwTzV3Vo);
        }
    }
}